from app import db
from datetime import datetime

class SystemLog(db.Model):
    __tablename__ = 'system_logs'
    
    log_id = db.Column(db.BigInteger, primary_key=True, autoincrement=True, comment='日志ID')
    trace_id = db.Column(db.String(100), nullable=False, comment='追踪ID(用于关联一次请求的所有日志)')
    trace_module = db.Column(db.String(100), nullable=False, comment='追踪模块')
    trace_content = db.Column(db.Text, nullable=False, comment='追踪内容')
    log_level = db.Column(db.Enum('DEBUG', 'INFO', 'WARN', 'ERROR', 'FATAL'), nullable=False, default='INFO', comment='日志级别')
    user_id = db.Column(db.BigInteger, db.ForeignKey('users.id'), nullable=True, comment='操作用户ID')
    ip_address = db.Column(db.String(45), nullable=True, comment='IP地址')
    user_agent = db.Column(db.Text, nullable=True, comment='用户代理')
    created_at = db.Column(db.DateTime, nullable=False, default=datetime.utcnow, comment='创建时间')
    
    # Define indexes
    __table_args__ = (
        db.Index('idx_trace_id', trace_id),
        db.Index('idx_trace_module', trace_module),
        db.Index('idx_log_level', log_level),
        db.Index('idx_created_at', created_at),
        db.Index('idx_user_id', user_id),
    )
    
    # Define relationships
    user = db.relationship('User', foreign_keys=[user_id], backref=db.backref('system_logs', lazy=True))
    
    def __repr__(self):
        return f'<SystemLog {self.log_id}>'